-- UIMagicAnvil
-- Created by huanghr April/7/2016
-- 大附魔师的铁砧

require "game/ui/form/equips/UIEquipTooltip"
require "game/ui/form/equips/UIEquips"

-- UIMagicAnvil 继承自Layer
UIMagicAnvil = class("UIMagicAnvil", function()
    return cc.Layer:create();
end);

function UIMagicAnvil.create(equipId, equipStyle)
    return UIMagicAnvil.new(equipId, equipStyle);
end

-- 内部函数声明
local resize;

-- 构造函数
function UIMagicAnvil:ctor(equipId, equipStyle)
    self:setName("UIMagicAnvil");

    -- 初始化
    local node = cc.CSLoader:createNode("layout/risker_equip/Anvil.csb");
    self:addChild(node);
    self.node = node;

    self:setLocalZOrder(UIMgr.TOP_MENU_ZORDER + 1);

    self.toolEquip = equipId;

    -- 记录源装备
    self.srcEquipId = nil;
    self.isEquiped  = false;

    self.equipStyle = equipStyle;

    -- 注册事件处理回调函数
    self:registerEventCallback()

    -- 注册点击事件
    self:registerTouchEvent();

    -- 重绘
    self:redraw();

    -- 适配
    resize(node);
end

-- 适配
function resize(node)
    -- bg居中显示并充满整个屏幕
    AlignM.fitToScreen(node, "bg");

    -- CT居中并缩放至合适大小
    AlignM.alignToCenter(node, "CT");

    -- BT置于底部并缩放至合适大小
    AlignM.alignToBottomCenter(node, "BT");
end

-- 注册事件处理回调函数
function UIMagicAnvil:registerEventCallback()
    -- 关注工坊放入装备的事件
    EventMgr.register("UIMagicAnvil", event.BLACKSMITH_INPUT_EQUIP, function(args)
        self:whenInputEquip(args);
    end);

    -- 关注装备升级事件
    EventMgr.register("UIMagicAnvil", event.RISKER_UPGRADE_EQUIP, function(args)
        self:whenUpgradeEquip(args);
    end);

    -- 显示TOPMENU
    EventMgr.register("UIMagicAnvil", event.FOCUS_CHANGED, function(para)
        if para["get"] == "UIMagicAnvil" then
            UIMgr:getCurrentScene().topMenu:show(TOPMENU_FRAME_MONEY, TOPMENU_FRAME_GEM);
            UIMgr:getCurrentScene().topMenu:setLocalZOrder(UIMgr.TOP_MENU_ZORDER + 1);
        end
    end);

    -- 界面析构后，需要清理下
    self:registerScriptHandler(function(ev)
        if ev == "exit" then
            -- 还原TopMenu的ZOrder
            local topMenu = UIMgr.getCurrentScene().topMenu;
            if topMenu then
                topMenu:setVisible(self.oldVisible);
                topMenu:setLocalZOrder(self.oldZOrder);
            end

            EventMgr.removeAll("UIMagicAnvil");

            -- 显示装备合成页面
            if not UIMgr.getCurrentScene():isOpen("UIEquips") then
                local uiTreasure = UIEquips.create();
                UIMgr.getCurrentScene():addForm(uiTreasure);
            end

        elseif ev == "enter" then
            -- 临时调高TOP_MENU的ZOrder
            local topMenu = UIMgr:getCurrentScene().topMenu;
            self.oldVisible = topMenu:isVisible();
            UIMgr.getCurrentScene().topMenu:setVisible(true);
            self.oldZOrder = topMenu:getLocalZOrder();

            -- 关闭上层页面
            if UIMgr.getCurrentScene():isOpen("UIEquipsOperation") then
                UIMgr.getCurrentScene():removeFormByName("UIEquipsOperation");
            end
        end
    end);
end

-- 注册点击事件
function UIMagicAnvil:registerTouchEvent()
    local node = self.node;

    -- 注册返回按钮点击事件
    local btnBack = findChildByName(node, "BT/btn_back");
    local function onBackClick(sender, eventType)
        if eventType == ccui.TouchEventType.ended then
            AudioM.playFx("button_return");
            -- 关闭当前界面
            UIMgr.getCurrentScene():removeFormByName("UIMagicAnvil");
        end
    end
    AddBackEventHandler(self, btnBack, onBackClick);

    -- 注册确定按钮点击事件
    local btnOk = findChildByName(node, "CT/btn_ok");
    local function onOkClick(sender, eventType)
        if eventType == ccui.TouchEventType.ended then
            local classId = self.srcEquipId;
            if not classId then
                local title = getLocStr("dungeon_black_smith_tip");
                local tip   = getLocStr("dsct_equip_click");
                showHint2(title, tip);
            else
                AudioM.playFx("button_select");
                local cost = RiskerEquipM.getUpgradeMagicSuitCost(classId)
                if ItemM.getAmount(ME.user, cost[2]) < cost[3] then
                    -- 不够消耗
                    local itemName = ItemM.query(cost[2], "name");
                    alert(string.format(getLocStr("upgrade_not_cost_enough"), itemName));
                    return;
                end

                -- 升级装备
                if self.isEquiped then
                    local ret = FormulaM.invoke("FORBID_UPGRADE_WEAR_EQUIP", ME.user, self.classId);
                    if ret then
                        -- 探索点不足
                        alert(getLocStr("forbid_upgrade_suit_" .. ret));
                        return;
                    end

                    -- 如果是已穿戴的装备，先尝试脱下来
                    local equipType = EquipM.query(classId, "type");
                    if DungeonActionM.go("do_unequip", 1, equipType) then
                        DungeonActionM.go("upgrade_suit", self.equipStyle, classId);
                    end
                else
                    -- 未穿戴的装备，直接升级
                    DungeonActionM.go("upgrade_suit", self.equipStyle, classId);
                end
                -- RiskerEquipM.upgradeEquip(self.srcEquipId, self.isEquiped, self.equipStyle);
            end
        end
    end
    btnOk:addTouchEventListener(onOkClick);

    -- 注册源装备点击事件
    local equipGrid = findChildByName(node, "CT/src_node/bg");
    local function onEquipClick(sender, eventType)
        if eventType == ccui.TouchEventType.ended then
            AudioM.playFx("button_click");
            -- 打开装备选择界面
            -- 传入参数：通过工坊打开
            UIMgr.getCurrentScene():removeFormByName("UIEquips");
            local uiEquip = UIEquips.create(EQUIP_OPEN_TYPE_ANVIL, {["upgradeStyle"] = self.equipStyle, ["keepEquips"] = 1});
            UIMgr.getCurrentScene():addForm(uiEquip);
        end
    end
    equipGrid:addTouchEventListener(onEquipClick);

    -- 注册目标装备点击事件
    local dsctEquipImg = findChildByName(node, "CT/dst_node/icon");
    local equipImg = findChildByName(node, "CT/equip_img");
    dsctEquipImg:setTouchEnabled(true);
    local function onDstEquipClick(sender, eventType)
        if eventType == ccui.TouchEventType.ended then
            if not self.srcEquipId then
                local title = getLocStr("dungeon_black_smith_tip");
                local tip   = getLocStr("dsct_equip_click");
                showHint2(title, tip);
            else
                AudioM.playFx("button_click");
                -- 查看装备悬浮
                showEquipTooltip(self.dstEquipId);
            end
        end
    end
    dsctEquipImg:addTouchEventListener(onDstEquipClick);
    equipImg:addTouchEventListener(onDstEquipClick);
end

-- 重绘
function UIMagicAnvil:redraw()
    local CT = findChildByName(self.node, "CT");
    local BT = findChildByName(self.node, "BT");

    -- 显示标题
    local title = ItemM.query(self.toolEquip, "name");

    -- 标题
    local titleLabel = findChildByName(CT, "title_label");
    TextStyleM.setTitleStyle(titleLabel);
    titleLabel:setString(title);
    titleLabel:setPosition(titleLabel:getPositionX(), titleLabel:getPositionY());

    -- 副标题
    local subTitleLabel = findChildByName(CT, "sub_title");
    TextStyleM.setSubheadStyle(subTitleLabel);
    subTitleLabel:setString(getLocStr("upgrade_equip_title"));

    -- 显示当前消耗
    self:redrawCost();

    -- 显示确定按钮
    local btnOk = findChildByName(CT, "btn_ok");
    TextStyleM.setTextStyle(btnOk, TextStyleM.TEXT_SIZE_MIDDLE, TextStyleM.TEXT_COLOR_BROWN_YELLOW, true);
    btnOk:setTitleText(getLocStr("btn_text_upgrade_suit"));

    -- 显示返回按钮
    local btnBack = findChildByName(BT, "btn_back");
    TextStyleM.setTextStyle(btnBack, TextStyleM.TEXT_SIZE_MIDDLE, TextStyleM.TEXT_COLOR_BROWN_YELLOW, true);
    btnBack:setTitleText(getLocStr("btn_text_back"));

    -- 重绘当前提示
    self:redrawTip();

    -- 显示装备
    self:redrawEquip();
end

-- 显示消耗
function UIMagicAnvil:redrawCost()
    -- 显示消耗，
    local costNode = findChildByName(self.node, "CT/cost_node");
    local spImg = findChildByName(costNode, "cost_icon");
    local spLabel = findChildByName(costNode, "amount_label");
    local icon = ItemM.query(7303, "icon");
    spImg:loadTexture(getItemIconPath(icon));
    spLabel:setVisible(true);

    if not self.srcEquipId then
        spLabel:setVisible(false);
    else
        local cost = RiskerEquipM.getUpgradeMagicSuitCost(self.srcEquipId);
        local amount = cost[3];
        TextStyleM.setTextStyle(spLabel, TextStyleM.TEXT_SIZE_SMALL2, TextStyleM.TEXT_COLOR_DARK_BROWN, true);

        spLabel:setVisible(true);

        -- 探索点不足,数量显示为红色，否则蓝色
        local strNum;
        local btnOk = findChildByName(self.node, "CT/btn_ok");

        if ItemM.getAmount(ME.user, cost[2]) < amount then
            strNum = "[light_red]" .. amount .. "[-]";
            -- 按钮置灰
            btnOk:setBright(false);
            btnOk:setTouchEnabled(false);
        else
            strNum = "[yellow]" .. amount .. "[-]";
            btnOk:setBright(true);
            btnOk:setTouchEnabled(true);
        end

        spLabel = applyString(spLabel, strNum);
    end
end

-- 重绘装备
function UIMagicAnvil:redrawEquip()
    -- 初始化的时候显示默认的布局
    local equipImg = findChildByName(self.node, "CT/equip_img");
    local srcEquipImg = findChildByName(self.node, "CT/src_node/icon");
    local dstNode = findChildByName(self.node, "CT/dst_node");
    local dstEquipImg = findChildByName(dstNode, "icon");
    local dstEquipBg = findChildByName(dstNode, "bg");
    local srcEquipId = self.srcEquipId;
    srcEquipImg:setVisible(true);
    if not self.srcEquipId then
        equipImg:setVisible(true);
        dstEquipBg:setVisible(false);
        dstEquipImg:setVisible(false);
        equipImg:loadTexture("images/ui/building/blacksmith/anvil.png");
        checkAddBubbleStatus(srcEquipImg, nil, 0.8);
        return;
    end

    -- 显示源装备
    local srcIcon = ItemM.query(srcEquipId, "icon");
    local srcName = ItemM.query(srcEquipId, "name");

    srcEquipImg:loadTexture(getItemIconPath(srcIcon));

    -- 显示目标装备
    local dstEquipId = EquipM.query(srcEquipId, "next_class_id");
    local dstItemInfo = ItemM.query(dstEquipId);

    local dstRank = dstItemInfo["rank"];
    local srcRank = ItemM.query(srcEquipId, "rank");

    -- 都到这了，肯定能取到目标装备的信息
    assert(dstItemInfo);

    -- 记录目标装备
    if not self.srcEquipId then
        equipImg:setVisible(true);
        dstEquipBg:setVisible(false);
        dstEquipImg:setVisible(true);
        dstEquipImg:loadTexture("images/ui/building/blacksmith/anvil.png");
    else
        equipImg:setVisible(false);
        dstEquipBg:setVisible(true);
        dstEquipImg:setVisible(true);

        local dstStarNode = findChildByName(dstNode, "star_node");

        local layer = createStarLayer(dstRank, "images/ui/symbol/star_little.png", "center", -0.6);
        if layer then
            dstStarNode:removeAllChildren();
            dstStarNode:addChild(layer);
        end


        local srcStar = findChildByName(self.node, "CT/src_node/star_node");

        local srclayer = createStarLayer(srcRank, "images/ui/symbol/star_little.png", "center", -0.6);
        if srclayer then
            srcStar:removeAllChildren();
            srcStar:addChild(srclayer);
        end

        local dstIcon = ItemM.query(dstEquipId, "icon");
        dstEquipImg:loadTexture(getItemIconPath(dstIcon));
        srcEquipImg:stopAllActions();
    end

    self.dstEquipId = dstEquipId;
end

-- 重绘提示
function UIMagicAnvil:redrawTip()
    local tipLabel = findChildByName(self.node, "CT/tip_label");
    -- 记录目标装备
    TextStyleM.setTextStyle(tipLabel, TextStyleM.TEXT_SIZE_SMALL2, TextStyleM.TEXT_COLOR_DARK_BROWN);

    if not self.srcEquipId then
        if self.equipStyle == EQUIP_STYLE_MAGIC then
            applyString(tipLabel, getLocStr("upgrade_magic_suit_tip"));
        else
            applyString(tipLabel, getLocStr("upgrade_physic_suit_tip"));
        end
    else
        -- 根据消耗显示
        local cost = RiskerEquipM.getUpgradeMagicSuitCost(self.srcEquipId);
        local amount = cost[3];

        local hasAmount = ItemM.getAmount(ME.user, cost[2]);

        -- 探索点不足,数量显示为红色，否则蓝色
        local name = ItemM.query(cost[2], "name");

        local equipName = ItemM.query(self.srcEquipId, "name");
        local upgradeText = string.format(getLocStr("upgrade_equip"), equipName);

        local costText = string.format(getLocStr("compound_spell_cost_rune"), name, hasAmount, amount);
        if hasAmount < amount then
            costText = "[red]" .. costText .. "[-]";
        else
            costText = "[blue]" .. costText .. "[-]";
        end

        local tipText = upgradeText .. "\n" .. costText;

        applyString(tipLabel, tipText);
    end
end

-- 装备升级成功的回调
function UIMagicAnvil:whenUpgradeEquip(args)
    -- 使用默认提示
    AudioM.playFx("furnace");

    -- 关闭界面
    UIMgr.getCurrentScene():removeFormByName("UIMagicAnvil");
end

-- 工坊放入装备的回调
function UIMagicAnvil:whenInputEquip(args)
    local srcEquipId = args.classId;
    if not srcEquipId then
        return;
    end

    -- 记录装备id
    self.srcEquipId = srcEquipId;
    self.isEquiped = args.isEquiped;

    -- 重绘装备格
    self:redrawEquip();

    self:redrawCost();

    -- 重绘提示
    self:redrawTip()
end
